package com.sprucetec.live.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 文件Hash值计算
 */
public class FileEncryptUtil {
	
	/**
	 * 对文件加密,加密算法使用 MD5,SHA-1,SHA-256,SHA-384 SHA-512 默认使用SHA-1
	 */
	public static String encrypt(File file, String encName) {
		if (!file.isFile()) {
			return null;
		}
		
		MessageDigest md = null;
		FileInputStream in = null;
		byte buffer[] = new byte[2048];
		int len;
		
		try {
			if (encName == null || encName.equals("")) {
				encName = "SHA-1";
			}
			md = MessageDigest.getInstance(encName);
			in = new FileInputStream(file);
			while ((len = in.read(buffer, 0, 2048)) != -1) {
				md.update(buffer, 0, len);
			}
			in.close();
		} catch (NoSuchAlgorithmException | IOException e) {
			return null;
		} finally {
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		BigInteger bigInt = new BigInteger(1, md.digest());
		return bigInt.toString(16);
	}
	
	/**
	 * 对文件加密,加密算法使用 MD5,SHA-1,SHA-256,SHA-384 SHA-512 默认使用SHA-1
	 */
	public static String encrypt(InputStream in, String encName) {
		
		MessageDigest md = null;
		byte buffer[] = new byte[2048];
		int len;
		try {
			if (encName == null || encName.equals("")) {
				encName = "SHA-1";
			}
			md = MessageDigest.getInstance(encName);
			while ((len = in.read(buffer, 0, 2048)) != -1) {
				md.update(buffer, 0, len);
			}
			//in.close();
		} catch (NoSuchAlgorithmException e) {
			return null;
		} catch (IOException e) {
			return null;
		}
		BigInteger bigInt = new BigInteger(1, md.digest());
		return bigInt.toString(16);
	}
	
	
	
}
